import * as bcrypt from 'bcryptjs';
import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { LoginDto } from './dto/LoginDto';
import { UserService } from 'src/module/system/user/user.service';
import { Result } from 'src/utils/result';
import { ConfigService } from '@nestjs/config';
import { decryptRSA } from 'src/utils/secret';

@Injectable()
export class AuthService {
  constructor(
    private jwt: JwtService,
    private userService: UserService,
    private configService: ConfigService,
  ) {}

  // 登录
  async login(loginDto: LoginDto) {
    const user = await this.userService.findOneByName(loginDto.username);
    if (!user) {
      return Result.fail('用户不存在');
    }
    loginDto.password = decryptRSA(loginDto.password);

    if (!bcrypt.compareSync(loginDto.password, user.password)) {
      return Result.fail('账号密码有误');
    }
    const payload = { sub: user.userId, username: loginDto.username };

    const token = await this.createToekn(payload);
    return Result.success({ token });
  }

  // 创建token
  async createToekn(payload: { sub: number; username: string }) {
    return this.jwt.sign(payload, {
      secret: this.configService.get('jwt.secret'),
    });
  }
  // 校验用户
  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.userService.findOneByName(username);
    if (user && bcrypt.compareSync(pass, user.password)) {
      const { password, ...result } = user;
      return result;
    }
    return null;
  }
}
